Practice Problems on Structures and Unions in C

Posted on December 18, 2023 by Vishesh Namdev
Python C C++ Java
C Programming Language

Basic Practice Problems based on chapter which you learn in previous Tutorials.

1. Store Information of Students using Structure

#include <stdio.h>Copy Code
// Define a structure to represent a student
struct Student {
char name[50];
int rollNumber;
float marks;
};

int main() {
// Declare an array of structures to store information about multiple students
struct Student students[3];

// Input information for each student
for (int i = 0; i < 3; i++) {
printf("Enter details for student %d:\n", i + 1);

printf("Name: ");
scanf("%s", students[i].name);

printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);

printf("Marks: ");
scanf("%f", &students[i].marks);

printf("\n");
}

// Display information for each student
printf("Student Information:\n");
for (int i = 0; i < 3; i++) {
printf("Student %d\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Marks: %.2f\n", students[i].marks);
printf("\n");
}

return 0;
}

2. Difference between Two Time Periods

#include <stdio.h>Copy Code
struct Time {
int hours, minutes, seconds;
};

struct Time timeDifference(struct Time t1, struct Time t2) {
struct Time diff;
int totalSeconds1 = t1.hours * 3600 + t1.minutes * 60 + t1.seconds;
int totalSeconds2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;
int differenceInSeconds = totalSeconds1 - totalSeconds2;
diff.hours = differenceInSeconds / 3600;
differenceInSeconds %= 3600;
diff.minutes = differenceInSeconds / 60;
diff.seconds = differenceInSeconds % 60;
return diff;
}

int main() {
struct Time time1, time2;
printf("Enter first time (hours minutes seconds): ");
scanf("%d %d %d", &time1.hours, &time1.minutes, &time1.seconds);

printf("Enter second time (hours minutes seconds): ");
scanf("%d %d %d", &time2.hours, &time2.minutes, &time2.seconds);

struct Time difference = timeDifference(time1, time2);
printf("Time Difference: %d hours, %d minutes, %d seconds\n",
difference.hours, difference.minutes, difference.seconds);

return 0;
}